package com.funcourse.demo.api.restful.security;

import com.funcourse.demo.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;

@Slf4j
@Service
public class ActivactionFilter implements Filter {

    @Autowired
    AuthUserHolder authUserHolder;

    Pattern activeFilterExceptencUri = Pattern.compile("/api/v\\dd\\d/organize/activateAccount");

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        User authUser = authUserHolder.getAuthUser();
        if (null == authUser) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.sendError(403);
        } else if (null!= authUser.getActivated() && !authUser.getActivated() && !activeFilterExceptencUri.matcher(((HttpServletRequest) request).getRequestURL()).find()) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.sendError(401);
        } else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }
}
